package com.diandian.backend.kuaishou.life.task.service;

import com.alibaba.fastjson.JSON;
import com.diandian.backend.kuaishou.life.task.dto.KuaishouLifeTokenListParamDTO;
import com.diandian.backend.kuaishou.life.task.resp.KuaishouLifeTokenListResp;
import com.diandian.dingtalk.boot.starter.sender.DingTalkMessageSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class BusinessRefreshTokenCheckService {

    private static final Logger logger = LoggerFactory.getLogger(BusinessRefreshTokenCheckService.class);

    @Autowired
    private BusinessKuaishouLifeTokenService businessKuaishouLifeTokenService;

    @Autowired
    private DingTalkMessageSender dingTalkMessageSender;

    private final int REMINDER_DAYS_COUNT = 7;

    public void refreshTokenCheck(){

        // 查询所有的token信息
        KuaishouLifeTokenListParamDTO listParamDTO = new KuaishouLifeTokenListParamDTO();
        listParamDTO.setDel(0);
        List<KuaishouLifeTokenListResp> tokenList = businessKuaishouLifeTokenService.getList(listParamDTO);
        if(tokenList == null || tokenList.size() == 0){
            logger.info("查询到token集合数据为0，停止后续处理");
            return;
        }
        logger.info("共查询到token记录条数：{}", tokenList.size());

        // 校验，过滤出不合法的数据
        Date endDate = calculateEndDate();
        String endDateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endDate);
        List<KuaishouLifeTokenListResp> errorList = new ArrayList<>();
        for (int i = 0; i < tokenList.size(); i++) {
            Date refreshTokenEndDate = tokenList.get(i).getExpiresDateRefreshToken();
            if(refreshTokenEndDate == null){
                logger.info("第{}条记录Refresh Token过期时间为空，请及时处理，详细数据：{}", i + 1, JSON.toJSONString(tokenList.get(i)));
                errorList.add(tokenList.get(i));
                continue;
            }
            if(refreshTokenEndDate.before(endDate)){
                logger.info("第{}条记录Refresh Token即将过期，请及时处理，详细数据：{}", i + 1, JSON.toJSONString(tokenList.get(i)));
                errorList.add(tokenList.get(i));
            }
        }
        logger.info("查询到Refresh Token即将过期(截止{})记录数：{}", endDateStr, errorList.size());

        String message = (errorList.size() > 0) ? "快手本地生活Refresh Token即将过期(不足" + REMINDER_DAYS_COUNT + "天)数量: " + errorList.size() +"，请及时关注处理。" : "快手本地生活全部Refresh Token状态正常。";
        try {
            dingTalkMessageSender.sendTextMessage(message);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private Date calculateEndDate(){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.add(Calendar.DAY_OF_MONTH, REMINDER_DAYS_COUNT);
        return calendar.getTime();
    }
}
